﻿using System.Data;
using System.Xml.Linq;
using System.Xml.XPath;
using PengSW.RuntimeLog;

namespace PengSW.XmlDb
{
    public class XmlImport
    {
        public XmlImport(XmlToTableRules aTableRules)
        {
            TableRules = aTableRules;
        }

        public XmlToTableRules TableRules { get; private set; }

        public void ImportTableToDataSet(DataSet aDataSet, XmlToTableRule aTableRule, XElement aRootXElement, string aParentId)
        {
            DataTable aDataTable = aDataSet.Tables[aTableRule.TableName];
            // 导入数据
            foreach (XElement aRecordXElement in aRootXElement.XPathSelectElements(aTableRule.XPath))
            {
                DataRow aDataRow = aDataTable.NewRow();
                string aId = PengSW.Id.UniqueId.GetSId();
                foreach (XmlToFieldRule aFieldRule in aTableRule.FieldRules)
                {
                    string aValue = "";
                    if (aFieldRule.XPath.Trim() != string.Empty)
                    {
                        XElement aFieldXElement = aRecordXElement.XPathSelectElement(aFieldRule.XPath);
                        aValue = aFieldXElement == null ? aFieldRule.DefaultValue : aFieldXElement.Value;
                    }
                    else if (aFieldRule.FieldName == aTableRule.IdFieldName)
                    {
                        aValue = aId;
                    }
                    else if (aFieldRule.FieldName == aTableRule.ParentIdFieldName)
                    {
                        aValue = aParentId;
                    }
                    aDataRow[aFieldRule.FieldName] = aValue;
                }
                try
                {
                    aDataTable.Rows.Add(aDataRow);
                }
                catch (System.Exception ex)
                {
                    RL.L(string.Format("{2}: {0} {1}", aDataRow["Id"], aDataRow["ParentId"], ex.Message));
                }

                // 导入子表
                foreach (XmlToTableRule aSubTableRule in aTableRule.SubTableRules)
                {
                    ImportTableToDataSet(aDataSet, aSubTableRule, aRecordXElement, aId);
                }
            }
        }

        public void ImportToDataSet(DataSet aDataSet, XElement aRootXElement)
        {
            TableRules.CreateDataTablesInto(aDataSet);

            foreach (XmlToTableRule aTableRule in TableRules)
            {
                ImportTableToDataSet(aDataSet, aTableRule, aRootXElement, "");
            }
        }
    }
}
